import * as React from "react"
import type { SelectionRange } from "@glideapps/glide-data-grid"
import { NumericFormat } from "react-number-format"
import type { NumberFormatValues } from "react-number-format/types/types.js"

interface Props {
  readonly value: number | undefined
  readonly disabled?: boolean
  readonly onChange: (values: NumberFormatValues) => void
  readonly highlight: boolean
  readonly validatedSelection?: SelectionRange
  readonly fixedDecimals?: number
  readonly allowNegative?: boolean
  readonly thousandSeparator?: boolean | string
  readonly decimalSeparator?: string
}

function getDecimalSeparator() {
  const numberWithDecimalSeparator = 1.1
  const result = Intl.NumberFormat()
    ?.formatToParts(numberWithDecimalSeparator)
    ?.find((part) => part.type === "decimal")?.value

  return result ?? "."
}

function getThousandSeprator() {
  return getDecimalSeparator() === "." ? "," : "."
}

const NumberOverlayEditor: React.FunctionComponent<Props> = (p) => {
  const {
    value,
    onChange,
    disabled,
    highlight,
    validatedSelection,
    fixedDecimals,
    allowNegative,
    thousandSeparator,
    decimalSeparator,
  } = p

  const inputRef = React.useRef<HTMLInputElement>()

  React.useLayoutEffect(() => {
    if (validatedSelection !== undefined) {
      const range =
        typeof validatedSelection === "number"
          ? [validatedSelection, null]
          : validatedSelection
      inputRef.current?.setSelectionRange(range[0], range[1])
    }
  }, [validatedSelection])

  return (
    <div className="flex my-1.5 mb-1 text-[var(--gdg-text-dark)]">
      <NumericFormat
        autoFocus={true}
        getInputRef={inputRef}
        className="gdg-input text-[var(--gdg-editor-font-size)] p-0 font-[var(--gdg-font-family)] text-[var(--gdg-text-dark)] bg-[var(--gdg-bg-cell)]"
        onFocus={(e: React.FocusEvent<HTMLInputElement>) =>
          e.target.setSelectionRange(
            highlight ? 0 : e.target.value.length,
            e.target.value.length
          )
        }
        disabled={disabled === true}
        decimalScale={fixedDecimals}
        allowNegative={allowNegative}
        thousandSeparator={thousandSeparator ?? getThousandSeprator()}
        decimalSeparator={decimalSeparator ?? getDecimalSeparator()}
        value={Object.is(value, -0) ? "-" : (value ?? "")}
        // decimalScale={3}
        // prefix={"$"}
        onValueChange={onChange}
      />
    </div>
  )
}

export default NumberOverlayEditor
